﻿using _9jCardRegisterCollection.Helper;
using _9jCardRegisterCollection.Models;
using AntdUI;
using CardRegisterCollection.BLL;
using CardRegisterCollection.Model;
using CardRegisterCollection.Utility;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;

namespace _9jCardRegisterCollection.Views
{
    public partial class DomesticImportExcel : Form
    {
        public DomesticImportExcel(AntdUI.Window window)
        {
            InitializeComponent();
            Window = window;
        }
        CardRegisterCollection.BLL.DomesticAttendee domesticAttendeeBll = new CardRegisterCollection.BLL.DomesticAttendee();
        AntdUI.Window Window;

        CardRegisterCollection.BLL.CardType cardTypeBll = new CardRegisterCollection.BLL.CardType();

        private void button_ok_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "消息:";
            var dig = new OpenFileDialog()
            {
                Title = "请选择要导入的文件",
                Filter = "Excel Files|*.xlsx;*.xls",
                Multiselect = false//是否可以多选文件

            };
            //选择文件时取消
            if (dig.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var inputFilename = dig.FileName;
            //返回指定的路径字符串的扩展名,Extension扩展
            var ext = Path.GetExtension(inputFilename);
            DataTable data = new DataTable();
            try
            {
                data = ExcelToTable(inputFilename);
            }
            catch (Exception ex)
            {
                AntdUI.Message.warn(Window, ex.Message, autoClose: 1);
                return;
            }
            DataColumn dc1 = new DataColumn("错误信息", typeof(string));
            data.Columns.Add(dc1);
            ExcelDataCheck(data);

            this.dataGridView1.DataSource = data;
        }

        private void ExcelDataCheck(DataTable dataTable)
        {
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                dataTable.Rows[i]["错误信息"] = CheckInputIDNumber(dataTable.Rows[i]["身份证件号码"].ToString(), dataTable.Rows[i]["性别"].ToString(), i + 1);
            }
        }


        /// <summary>
        /// 检验身份证号
        /// </summary>
        /// <param name="idNumberValue"> 身份证号</param>
        /// <param name="fieldGenderm">性别</param>
        /// <param name="rowIndex">行号</param>
        private string CheckInputIDNumber(string idNumberValue, string fieldGenderm, int rowIndex)
        {
            string wrongMessage = CheckUserInputHelper.CheckInputIDNumber(idNumberValue);
            if (domesticAttendeeBll.Exit(idNumberValue))
            {
                wrongMessage += "该人员已存在,请检查身份证号是否有误;";
            }
            if (wrongMessage.Length == 0 && !CheckUserInputHelper.GetIDNumberGender(idNumberValue).Equals(fieldGenderm))
            {
                wrongMessage += "身份证号与性别对应错误";
            }
            if (wrongMessage.Length > 0)
            {
                richTextBox1.Text += "\n第 " + rowIndex + " 行  " + wrongMessage;
            }
            return wrongMessage;
        }
        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) { return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

         
        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueType(NPOI.SS.UserModel.ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
       e.RowBounds.Location.Y,
       dataGridView1.RowHeadersWidth - 4,
       e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count == 0)
            {
                AntdUI.Message.warn(Window,"当前数据为空，请重新导入数据！",autoClose:1);
                return;
            }
            var result = AntdUI.Modal.open(Window, "操作提示！", "该操作会自动跳过存在异常的数据，只对符合条件的数据进行导入，是否继续？", TType.Warn);
            if (result == DialogResult.No)
            {
                return;
            }
            string group = dataGridView1.Rows[0].Cells["组别"].Value.ToString();
            for (int i = 1; i < dataGridView1.Rows.Count; i++)
            {
                if (dataGridView1.Rows[i].Cells["错误信息"].Value.ToString().Length > 0)
                {
                    continue;
                }
                CardRegisterCollection.Model.DomesticAttendee domesticAttendee = new CardRegisterCollection.Model.DomesticAttendee();
                domesticAttendee.Id = Guid.NewGuid().ToString();
                domesticAttendee.Name = dataGridView1.Rows[i].Cells["人员姓名"].Value.ToString();
                domesticAttendee.Gender = dataGridView1.Rows[i].Cells["性别"].Value.ToString();
                domesticAttendee.IDNumber = dataGridView1.Rows[i].Cells["身份证件号码"].Value.ToString();
                domesticAttendee.WorkUnit = dataGridView1.Rows[i].Cells["工作单位"].Value.ToString();
                domesticAttendee.CardType = dataGridView1.Rows[i].Cells["办证类型"].Value.ToString();
                domesticAttendee.CreatedBy = CurrentLoginInfo.UserInfo.UserName;
                domesticAttendee.CreatedDate = DateTime.Now;
                domesticAttendee.UserDefine1 = group;
                domesticAttendeeBll.Add(domesticAttendee);
            }
            AntdUI.Message.success(Window, "批量添加成功", autoClose: 1);
            this.Close();
        }
        private void label5_Click(object sender, EventArgs e)
        {
            string strSelectedPath = SelectedFolderPath();
            if (string.IsNullOrWhiteSpace(strSelectedPath))
            {
                return;
            }
            try
            {
                CreateCellDropDownList(strSelectedPath);
                AntdUI.Message.success(Window, "境内人员模板导出成功", autoClose: 1); 
            }
            catch (Exception ex) {
                AntdUI.Message.warn(Window, ex.Message, autoClose: 1);
            }
             
        }
        /// <summary>
        /// 生成excel下拉列表demo
        /// </summary>
        public void CreateCellDropDownList(string filePath)
        {
            filePath = filePath + "\\境内人员导入模板.xls";
            HSSFWorkbook workbook = new HSSFWorkbook();//从流内容创建Workbook对象
            ISheet sheet = workbook.CreateSheet("sheet1");//创建工作表

            HSSFRow row = (HSSFRow)sheet.CreateRow(0);//一行
            //列头
            List<string> list = new List<string> {
           "序号","人员姓名","性别","身份证件号码","工作单位","办证类型","组别"
           } ;



            HSSFCell[] cell = new HSSFCell[list.Count];//声明cell变量数组
            for (int i = 0; i < list.Count; i++)
            {
                cell[i] = (HSSFCell)row.CreateCell(i);//实例化单元格
                cell[i].SetCellValue(list[i]);//填写单元格
            }

            //设置生成下拉框的行和列
            CellRangeAddressList cellRegions = new CellRangeAddressList(1, 65535, 5, 5);


            //设置 下拉框内容
            DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(
                GetCardType());

            //绑定下拉框和作用区域，并设置错误提示信息
            HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint);
            dataValidate.CreateErrorBox("输入不合法", "请输入下拉列表中的值！");
            dataValidate.ShowPromptBox = true;

            sheet.AddValidationData(dataValidate);

            FileStream fs = new FileStream(filePath, FileMode.Create);
            workbook.Write(fs);
            fs.Close();
        }

        private string[] GetCardType()
        {
            //DataSet ds = cardTypeBll.GetList("ParentId <> \"0\" and DeleteFlag <> 1");
            DataSet ds = cardTypeBll.GetList(" DeleteFlag <> 1");
            if (ds.Tables[0].Columns.Count == 0)
            {
                return null;
            }
            string[] strings = new string[ds.Tables[0].Rows.Count];
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                strings[i] = ds.Tables[0].Rows[i]["name"].ToString();
            }
            return strings;
        }

        private string SelectedFolderPath()
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择导出文件路径";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                return dialog.SelectedPath;
            }
            return string.Empty;
        }
    }
}
